/**
 * 模拟Promise实现
 * @param {}} fn 
 */
function MyPromise(fn){
    // console.log(fn);
    let self = this;
    this.status = 'pending';
    this.value = undefined;//这是运行resolve函数时传入的参数
    this.errmsg = undefined; //这是运行reject函数时传入的参数

    //采用发布、订阅模式
    //这里是订阅这些回调事件
    this.resolvecallbacks = []; //用于保存resolve的回调函数
    this.rejectcallbacks = []; //用于保存reject的回调函数

    function resolve(val){
        //保证resolve执行的顺序是本轮事件循环的末尾
        setTimeout(() => {
            if(self.status === 'pending'){
                self.value = val;
                self.status = 'resolved';
                self.resolvecallbacks.forEach(callback=>{
                    callback(val)
                })
            }
        }, 0);
    }

    function reject(errmsg){
        setTimeout(() => {
            if(self.status === 'pending'){
                self.status = 'rejected';
                self.errmsg = errmsg;
                self.rejectcallbacks.forEach(callback=>{
                    callback(errmsg);
                })
            }
        }, 0);  
    }
    try{
        fn(resolve,reject);
    }catch(e){
        reject(e);
    }    
}
MyPromise.prototype.then = function(resolve,reject){
    let self = this;
    if(this.status === 'pending'){
        // console.log(resolve)
        this.resolvecallbacks.push(resolve);
        this.rejectcallbacks.push(reject);
    }
    if(this.status === 'resolved'){
        resolve(self.value)
    }
    if(this.status === 'rejected'){
        reject(self.errmsg);
    }

}

let p = new MyPromise(function(resolve,reject){
    //模拟异步调用
    setTimeout(() => {
        resolve("转成resolved");    
    }, 1000);
})
p.then(data=>{
    console.log(data);
},err=>{
    console.log(err);
});